<?php

/*

    MMetaverse - Open Metaverse Access Library

    Copyright (c) 2009 Mary Jane Soft - Marlon J. Manrique

    http://www.maryjanesoft.com
    http://www.marlonj.com

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General
    Public License along with this library; if not, write to the
    Free Software Foundation, Inc., 59 Temple Place, Suite 330,
    Boston, MA  02111-1307  USA

    $Id$

*/

/**
 * @package mjs.mmetaverse.manager
 */

require_once 'MDataBase.class.php';
require_once 'MRegion.class.php';

/**
 * Region Data Base
 */
class MRegionDB extends MDataBase {
    
    /**
     * Create the database access for the OpenSim object specified
     *
     * @param MMetaverse $metaverse current metaverse
     */
    public function MOSRegionDB(MMetaverse $metaverse) {
        $this->MOSDataBase($metaverse);
        $this->db = $this->getDatabase('regions');
    }

    /**
     * Returns an array with all the regions available in the grid
     *
     * @return MOSRegion[] Current regions
     */
    public function getRegions() {
        // Create an empty array to store region infos
        $regions = array();

        // Get region files names
        $fileNames = $this->getRegionFileNames();

        // Load the information from the xml file
        foreach ($fileNames as $fileName) {
            $regions[] = $this->loadRegionInfo($fileName);
        }

        // Return the array with the information of the regions
        return $regions;
    }

    /**
     * Return the information of the region from the xml file
     *
     * @param string $fileName The name of the xml file
     * @return MOSRegion The info of the region
     */
    private function loadRegionInfo($fileName) {
        // Load the xml
        $xml = simplexml_load_file($fileName);

        // Get the attributes of the Config node
        $attributes = $xml->Config->attributes();

        // Get region information
        $uuid = new MUUID((string) $attributes['sim_UUID'][0]);
        $name = (string) $attributes['sim_name'][0];
        $locationX = (string) $attributes['sim_location_x'][0];
        $locationY = (string) $attributes['sim_location_y'][0];
        $locationZ = (string) $attributes['sim_location_z'][0];
        $serverIP = (string) $attributes['internal_ip_address'][0];
        $serverPort = (string) $attributes['internal_ip_port'][0];

        // Create region info
        $region = new MRegion($uuid,$name,$locationX,$locationY,$locationZ,
            $serverIP,$serverPort);

        // Return region info
        return $region;
    }

    /**
     * Return the number of regions in the grid
     *
     * @return number of regions
     */
    public function getNumberOfRegions() {
        // Get the regions files
        $fileNames = $this->getRegionFileNames();
        // Return the count of files
        return count($fileNames);
    }

    /**
     * Return the name of the regions files
     *
     * @return string[] Names of the region file descriptors
     */
    public function getRegionFileNames() {
        // Create and empty array to store the filenames
        $files = array();

        // Get path to the opensim
        $config = $this->metaverse->getConfig();
        $path = $config->getOpenSimPath();

        // Open the dir to load the regions xml files
        $dir = opendir($path . '/Regions');

        // If the directory can't be open, throw an exception
        if(!$dir)
        {
            throw new Exception('Regions Directory dont exists');
        }

        // Read the xml files inside directory
        while(($file = readdir($dir)) !== false)
        {
            // Get the file extension
            $fileExtension = preg_replace('/^.*\./', '', $file);

            // If the file extension is xml load the information from the xml
            if($fileExtension == 'xml')
            {
                // Set the absolute filename
                $fileName = $path . '/Regions/' . $file;
                $files[] = $fileName;
            }
        }

        // Return the array with the filenames
        return $files;
    }

    /**
     * Return the region with the uuid specified
     *
     * @param MUUID uuid Region UUID
     */
    public function getRegion(MUUID $uuid) {
        // Get Regions
        $regions = $this->getRegions();

        // Seek the region with the uuid specified 
        foreach($regions as $region) {
            if($region->getUUID() == $uuid)
                return $region;
        }

        // If region not found throw an exception
        throw new Exception('Region Not Found');
    }
}

?>